'''MisacaSinaResolver

Author: Cauly Kan

Date: 2001.10.18

wiki: /wiki/MisacaConverterDesign.wiki

contact: cauliflower.kan@gmail.com

'''

import re

from urllib import urlopen
from xml.etree.ElementTree import fromstring

def VideoSourceResolve(vid, part = 1):
    
    '''
    VideoSourceResovle
    fetch info from sina video for specifed vid.
    params: vid, expecting a string like "vid=xxx", where xxx is a positive integer
    retval: None on error, otherwise a typical dict like {'timelength': 'xxx', 'vname': 'xxx', 'framecount': 'xxx', 'format': 'flv', 'urls': ['url1', 'url2']} would be returned.
    '''
    
    ret = {}
    
    m = re.match("^vid=([0-9]+)$", vid)
    
    if m is not None:
        
        vid = int(m.group(1))
    
        reader = urlopen("http://v.iask.com/v_play.php?vid=%d" % vid)
        
        size = 0

        #parse sina xml file
        xmltree = fromstring(reader.read())
        
        if xmltree.find('timelength') is not None:
        
            ret['timelength'] = _iter2string(xmltree.find('timelength').itertext())

        if xmltree.find('framecount') is not None:
            
            ret['framecount'] = _iter2string(xmltree.find('framecount').itertext())

        if xmltree.find('vname') is not None:
            
            ret['name'] = _iter2string(xmltree.find('vname').itertext())
        
        ret['format'] = "flv"
        
        #one video may be sliced into different tracks
        urls = []
        
        if xmltree.findall('durl') is not None:
            
            for item in list(xmltree.findall('durl')):
                
                urls.append(_iter2string(item.find('url').itertext()))
                
                size = size + int(_iter2string(item.find('length').itertext()))
               
        if size > 0:
                
            ret['urls'] = urls
            
            ret['size'] = size
        
    if len(ret) > 0:
        
        print "{:>20}".format("MisacaSinaResolver") + ": Found valid sina video '%s'" % ret['name']
        
        #for itm in ret['urls']:
            
            #print "{:>20}".format("MisacaSinaResolver") + ": Found urls '%s'" % itm

    #only return the result when urls are more then zero
    return ret if len(ret) > 0 else None

def _iter2string(obj):
    
    ret = list(obj)
    
    return ret[0]